package com.ai.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.web.cache.Constants;
import com.ai.web.cache.UserContext;
import com.ai.web.service.BgUserService;
import com.ai.web.util.MD5Util;
import com.ai.web.util.Utils;
import com.ai.web.vo.BgUserV;
import com.ai.web.vo.QueryData;
import com.ai.web.vo.ResultModel;
/**
 * 后台用户管理
* @ClassName: BgbgUserController 
* @Description: TODO 
* @author:  
* @date: 2014年3月28日
*
 */
@Controller
@RequestMapping("/bgUser")
public class BgUserController extends BaseController {
    
    
    private static Logger logger = Logger.getLogger(BgUserController.class);
    
    @Autowired
    private BgUserService bgUserService;
    
    @RequestMapping(value = "/list")
    public String list(@RequestParam(defaultValue = "") String username,
            @RequestParam(defaultValue = "") String password) {
        
        logger.info("hello......test");
        return "bgUser/bgUser_list";
    }
    
    @RequestMapping(value = "/modifyPasswordTemplate")
    public String modifyPasswordTemplate(@RequestParam(defaultValue = "") String username,
            @RequestParam(defaultValue = "") String password) {
        
        logger.info("hello......test");
        return "bgUser/modify-password";
    }
    
    
    @RequestMapping(value = "/query", produces = "application/json")
    @ResponseBody
    public QueryData query(@RequestParam HashMap<String, Object> paramMap)
            throws Exception {
        
        Map<String, Object> conditionMap = buildCondition(paramMap);
        logger.info("---- " + conditionMap);
        QueryData qd = bgUserService.queryListAndCount(conditionMap);
   	 	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<BgUserV> dataList = new ArrayList<BgUserV>();
        for(Object object:qd.getDataList()){
        	BgUserV bgUserV = (BgUserV)object;
             if(bgUserV.getCreateTime() != null){
            	 bgUserV.setCreateTimeStr(sdf.format(bgUserV.getCreateTime()));
             }
             dataList.add(bgUserV);
        }
        qd.setDataList(dataList);
        return qd;
    }
    
    @RequestMapping(value = "/new")
    public String newBgBgUser(Model model) {
        
        BgUserV bgUserV = new BgUserV();
        model.addAttribute("bgUserV", bgUserV);
        
        return "bgUser/bgUser_template";
    }
    
    @RequestMapping(value = "/update/{userId}")
    public String updateBgBgUser(@PathVariable("userId") int userId, Model model)
            throws Exception {
        
        BgUserV bgUserV = bgUserService.getBgUser(userId);
        logger.info("----- getUser:" + bgUserV);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(bgUserV.getCreateTime() != null){
        	bgUserV.setCreateTimeStr(sdf.format(bgUserV.getCreateTime()));
        }
        model.addAttribute("bgUserV", bgUserV);
        
        return "bgUser/bgUser_template";
    }
    
    @RequestMapping(value = "/checkPassword/{userId}")
    @ResponseBody
    public ResultModel checkPassword(@PathVariable("userId") int userId)
            throws Exception {
    	 ResultModel rm = new ResultModel();
    	 if(userId == 0){
    		 rm.setFailCode();
    	 }else{
	    	 BgUserV bgUserV = bgUserService.getBgUser(userId);
	    	 if(bgUserV.getId()>2 && MD5Util.validPassword(Constants.DEFAULT_PASSORD, bgUserV.getPassword())){
	    		 rm.setSuccessCode();
	    	 }
    	 }
    	 return rm;
    }
    
    @RequestMapping(value = "/save", produces = "application/json")
    @ResponseBody
    public ResultModel saveBgBgUser(BgUserV bgUserV) throws Exception {
        
        logger.info("-----save:" + bgUserV);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(!Utils.isEmpty(bgUserV.getCreateTimeStr())){
        	bgUserV.setCreateTime(sdf.parse(bgUserV.getCreateTimeStr()));
        }
        if(bgUserV.getId() == 0){
        	bgUserV.setPassword(MD5Util.getEncryptedPwd(Constants.DEFAULT_PASSORD));
        	bgUserV.setCreateTime(new Date());
        }
        ResultModel rm = bgUserService.saveBgUser(bgUserV);
        return rm;
    }
    
    @RequestMapping(value = "/delete", produces = "application/json")
    @ResponseBody
    public ResultModel deleteBgBgUser(@RequestParam String delIds)
            throws Exception {
        
        System.out.println(delIds);
        
        List<Integer> userIds = getDeleteIds(delIds);
        ResultModel rm = bgUserService.deleteBgUsers(userIds);
        
        return rm;
    }
    
    @RequestMapping(value = "/password/reset/{userId}", produces = "application/json")
    @ResponseBody
    public ResultModel resetPassword(@PathVariable("userId")int userId) throws Exception {
        BgUserV BgUserV = bgUserService.getBgUser(userId);
        BgUserV.setPassword(MD5Util.getEncryptedPwd(Constants.DEFAULT_PASSORD));
        logger.info("-----save:" + BgUserV);
        return bgUserService.saveBgUser(BgUserV);
    }
    
    @RequestMapping(value = "/modifyPassword", produces = "application/json")
    @ResponseBody
    public ResultModel modifyPassword(String oldPassword, String newPassword, HttpServletRequest request) throws Exception {
    	ResultModel model = new ResultModel();
    	UserContext uc = (UserContext) request.getSession().getAttribute(Constants.USER_CONTEXT);
    	BgUserV user = bgUserService.getBgUser(uc.getBgUser().getId());
    	if(!MD5Util.validPassword(oldPassword, user.getPassword())){
    		model.setFailCode();
    		model.setMsg("原始密码不对!");
    		return model;
    	}else if(MD5Util.validPassword(newPassword, user.getPassword())){
    		model.setFailCode();
    		model.setMsg("新密码与旧密码一样!");
    		return model;
    	}else{
    		user.setPassword(MD5Util.getEncryptedPwd(newPassword));
    	}
        logger.info("-----save:" + user);
        return bgUserService.saveBgUser(user);
    }
}
